/* (c) 2008,2009 Jonathan Hogg and Andreas Grothey, University of Edinburgh
 *
 * This file is part of SML.
 *
 * SML is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, using version 3 of the License.
 *
 * SML is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

#include "Set.h"
#include "SyntaxNode.h"
#include "ListNode.h"
#include "data.tab.h"
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <map>
#include <string>
#include <vector>

using namespace std;

Set::Set(int dim_,string name_): dim(dim_),name(name_),card(0)
{
	LOG("Create set - name["<<name<<"] dim["<<dim<<"]");
}

void Set::addSetElement(SetValue* value)
{
	assert(value->valueList.size()==this->dim);
	LOG("Add SetValue index["<<card<<"] ["<<value->toString()<<"]");
	this->setValues.insert(pair<string,SetValue*>(value->getKey(),value));
	card++;
}

void Set::fillSetElements(string datalist)
{
	char* data = new char[datalist.length() + 1];
	strcpy(data,datalist.c_str());
	char* token;
	token = strtok(data,",() ");

	vector<string> toks;
	int tokenNum = 0;
	while(token!=NULL)
	{
		string tok(token);
		if(tokenNum%this->dim == 0 && toks.size()!=0)
		{
			SetValue* value = new SetValue(toks);
			this->addSetElement(value);
			toks.clear();
		}
		toks.push_back(tok);
		token = strtok(NULL,",() ");
		tokenNum++;
	}
	delete [] data;
}

Set::~Set()
{
	this->setValues.clear();
}

string Set::toString()
{
	ostringstream oss;
	map<string,SetValue*>::iterator i;
	for(i= this->setValues.begin();i!=this->setValues.end();i++)
	{
		oss<<(*i).second->toString();
	}
	return oss.str();
}
